<template>
  <div class="">
    <ProTable
        ref="proTableRef"
        :tableSource="tableData"
        :columns="columns"
        @onload="getList"
        @add="table_add"
        :initParam="{}"
    >

      <template #bodyCell="{record,column}">
        <template v-if="column.dataIndex === 'operation'">
          <ProButton type="link" :options="tableOption(record)" :cancel="tabke_item_cancel" :finished="(status)=>table_item_finished(status,record)"></ProButton>
        </template>
        <template v-else-if="column.dataIndex === 'dept_name'">
          {{ getValue(dept_tree,record.dept_id)}}
        </template>
        <!-- <template v-else-if="column.dataIndex === 'role_names'">
          {{$format.str(record.role_names)}}
        </template> -->
        <!-- <template v-else-if="column.dataIndex === 'disabled'">
          <Tag :color="record[column.dataIndex]?'#f50':globalStore.$state.config.themePrimary">
            {{  getValue(disabledList,String(record[column.dataIndex])) }}
          </Tag>
        </template> -->
        <template v-else>
          {{ record[column.dataIndex] }}
        </template>
      </template>
    </ProTable>

    <pro-modal v-model="visable" :title="is_add?'新增':'编辑'" @close="modal_cancel">
      <ProForm ref="lgformRef" :initParam="{}" :configure="configure"  v-bind="formOptions"></ProForm>
      <template #footer>
        <ProButton type="primary" :options="['submit','close']" :cancel="modal_cancel" :finished="modal_finished"></ProButton>
      </template>
    </pro-modal>

  </div>
</template>

<script setup lang="ts">
import fetchApiCommon from '@/api/common';
import fetchApi from "@/api/system/user";
import { buttonType } from "@/components/ProButton/interface";
import type { FormInstance, FormProps } from "@/components/ProForm";
import ProForm from "@/components/ProForm";
import type { TableInstance, TableProps } from "@/components/ProTable";
import ProTable from "@/components/ProTable";
// import { GlobalStore } from "@/store/modules/global";
import { get } from "lodash";
import { getCurrentInstance, nextTick, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
// const globalStore = GlobalStore()
const { locale } = useI18n({inheritLocale: true,useScope: 'local'})

const { proxy }:any = getCurrentInstance();

const tableData = ref<TableProps['tableSource']>({
  current:1,
  pageSize:20,
  total:0,
  list:[]
})

const disabledList = [
  {
    label:"禁用",
    value:"1",
    locale:{
      ch:"禁用",
      en:"disabled"
    }
  },
  {label:"启用",
    value:"0",
    locale:{
      ch:"启用",
      en:"enable"
    }
  }]

const columns = ref<TableProps['columns']>([
  {
    title:"用户名",
    dataIndex:"s_key",
    hidden:true,
    search:true
  },
  {
    title:"部门",
    dataIndex:"s_dept_id",
    hidden:true,
    searchType:"select",
    search:true,
    enum:[]
  },
  {
    title:"角色",
    dataIndex:"s_role_id",
    hidden:true,
    searchType:"select",
    search:true,
    enum:[]
  },
  {
    title:"用户名",
    dataIndex:"username",
  },
  {
    title:"姓名",
    dataIndex:"name",
  },
  {
    title:"部门",
    dataIndex:"dept_name",
  },
  {
    title:"角色",
    dataIndex:"role_names",
  },
  {
    title:"状态",
    dataIndex:"disabled",
    dic:disabledList
  },
  {
    width:270,
    dataIndex:"operation",
    title:"操作"
  }
])

const proTableRef = ref<TableInstance>();
const visable = ref(false);
const lgformRef = ref<FormInstance>();

const configure = ref<FormProps['configure']>([{"type":"text","label":"用户名","span":24,"prop":"username","searchInitParam":"","enum":[],
  "searchProps":{"disabled":false,"readonly":false,"required":true,"max":100},
  "rules":[{"type":"string","required":true,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"text","label":"姓名","span":24,"prop":"name","searchInitParam":"","enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":true,"max":100},
    "rules":[{"type":"string","required":true,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"password","label":"密码","span":24,"prop":"password","searchInitParam":"","enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":true,"max":100},
    "rules":[{"type":"string","required":true,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"text","label":"邮箱","span":24,"prop":"email","searchInitParam":"","enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":false,"max":100},
    "rules":[{"type":"string","required":false,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"select","label":"角色","span":24,"prop":"role_ids","searchInitParam":[],"enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":false,"mode":"multiple","maxTagCount":2},
    "rules":[{"type":"array","required":false,"trigger":["change","blur"]}]},
  {"type":"text","label":"电话","span":24,"prop":"mobile","searchInitParam":"","enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":false,"max":100},
    "rules":[{"type":"string","required":false,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"select","label":"部门","span":24,"prop":"dept_id","enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":false},
    "rules":[{"required":false,"trigger":["change","blur"]}]}])


const formOptions = {"showButton":false,"isvalidate":true,"layout":[6,14],"colNum":1}
const edit_info = ref<APISYSTEMUSER.SysUserItem|null>(null);
const is_add = ref(true);
const dept_tree = ref()


onMounted(()=>{
  getConfigure()
})

const getConfigure = async ()=>{
  const role = await fetchApiCommon.optionsRole();

  if(role.code === 200 && configure.value){
    proxy.$chain(configure.value)
    .find(['prop','role_ids'])
    .set('enum', role.data.map((v)=>({label:v.name,value:v.id}))).value()

    // const index = findIndex(configure.value,['prop',"role_ids"])
    // if(index !== -1 && configure.value){
    //   set(configure.value[index],'enum',role.data.map((v)=>({label:v.name,value:v.id})))
    // }

    proxy.$chain(columns.value)
    .find(['dataIndex','s_role_id'])
    .set('enum', role.data.map((v)=>({label:v.name,value:v.id}))).value()

    // const i = findIndex(columns.value,['dataIndex',"s_role_id"])
    // if(i !== -1 && columns.value){
    //   set(columns.value[i],'enum',role.data.map((v)=>({label:v.name,value:v.id})))
    // }
  }

  const dept = await fetchApiCommon.optionsDept();
  if(dept.code === 200 && configure.value){

    dept_tree.value = dept.data.map((v)=>({label:v.name,value:v.id}))

    proxy.$chain(configure.value)
    .find(['prop','dept_id'])
    .set('enum', dept_tree.value).value()

    proxy.$chain(columns.value)
    .find(['dataIndex','s_role_id'])
    .set('enum',dept_tree.value).value()


    // const index = findIndex(configure.value,['prop',"dept_id"])
    // if(index !== -1 && configure.value){
    //   set(configure.value[index],'enum',dept_tree.value)
    // }

    // const i = findIndex(columns.value,['dataIndex',"s_dept_id"])
    // if(i !== -1 && columns.value){
    //   set(columns.value[i],'enum',dept_tree.value)
    // }

  }

}


watch(()=>is_add.value,()=>{
  proxy.$chain(configure.value)
    .find(['prop','password'])
    .set('rules[0].required', is_add.value).value()

  // const index = findIndex(configure.value,['prop',"password"])
  // if(index !== -1 && configure.value) {
  //   set(configure.value[index],'rules[0].required',is_add.value)
  // }
},{
  immediate:false,
  deep:true
})

const getList = async (params:APISYSTEMUSER.SysUserParams)=>{
  const res = await fetchApi.sysUserList(params)
  if(res.code === 200 && tableData.value){
    tableData.value.list = res.data.list
    tableData.value.total = res.data.total
    tableData.value.pageSize = params.limit
    tableData.value.current = params.page
  }
}

// 表格行按钮点击事件
const table_item_finished = async (status:buttonType,item:APISYSTEMUSER.SysUserItem)=>{
  // if(['edit'].includes(status)) visable.value = true

    if(status === 'edit'){
      is_add.value = false

      visable.value = true
      await nextTick();
      await findUserInfo(item.id)
    }

  if(['disable','enable'].includes(status)){
    return  await table_disable(item,status)
  }


  if(status === 'delete'){
    return await table_delete(item)
  }
  return Promise.resolve()
}

const getValue = (list:any,value:any)=>{
  const item = proxy.$chain(list).find(['value',value]).value()
  if(item && item.locale){
    return item.locale[locale.value as "en" | "ch"]
  }
  return item && item.label ? item.label : '-'
}

// 获取用户信息
const findUserInfo = async (id:string)=>{
  const res = await fetchApi.sysUserFind(id)
  if(res.code === 200){
    edit_info.value = res.data

    lgformRef.value?.updateFormByKey('username',get(res,'data.username',''));
    lgformRef.value?.updateFormByKey('name',get(res,'data.name',''));
    lgformRef.value?.updateFormByKey('email',get(res,'data.email',''));
    lgformRef.value?.updateFormByKey('role_ids',get(res,'data.role_ids',[]));
    lgformRef.value?.updateFormByKey('mobile',get(res,'data.mobile',''));
    lgformRef.value?.updateFormByKey('dept_id',get(res,'data.dept_id',''));

  }
}

// 启用禁用
const table_disable = async (item:any,status:buttonType)=>{
  const res = await fetchApi.sysUserDisabled({id:item.id,disabled: status === 'disable' ? 1 : 0})
  proxy.$format.response(res)
  proTableRef.value?.refresh()
}

// 删除
const table_delete = async (item:APISYSTEMUSER.SysUserItem)=>{
  const res = await fetchApi.sysUserDel(item.id)
  proxy.$format.response(res)
  proTableRef.value?.refresh()
}

const table_add = ()=>{
  visable.value = true
}

const tabke_item_cancel = ()=>{
  alert("取消")
}


const modal_cancel = ()=>{
  console.log("点击取消")
  visable.value = false
  lgformRef.value?.resetForm()
  edit_info.value = null
  is_add.value = true
}
const modal_finished = async (status:buttonType)=> {
  switch (status){
    case "submit":
      return await modal_submit();
  }
}

// 提交
const modal_submit = async ()=>{
  try {
    const data = await lgformRef.value?.validate()
    if(!data) return false
    let res;
    if(!data.password) delete data.password
    if(is_add.value) res = await fetchApi.sysUserAdd({...data,role_ids:data.role_ids.join(',')});
    if(!is_add.value) res = await fetchApi.sysUserUpdate({...data,id:edit_info.value.id,role_ids:data.role_ids.join(',')});

    proxy.$format.response(res)
    proTableRef.value?.refresh();
    await modal_cancel()
  }catch (e) {
    console.log("提交",e)
  }
}

const tableOption = (record:any)=>{
  let list = ['edit','enable','disable','delete']
  if(record.username === 'admin') list = ['edit']
  return  proxy.$format.btn_del(proxy.$format.btn_disabled(list,record.disabled),record)
}

</script>

<style scoped lang="less">

</style>
